package org.lilred.nzbberry.http;


public class URL {
	private String _urlString;
	private String _host = null;
	private String _port = null;
	private String _path = null;
	
	public URL(String urlString) {
		this._urlString = urlString;
		parseUrl();
	}
	
	private void parseUrl() {
		int hostStart = _urlString.indexOf("//") + 2;
		if (hostStart == -1) throw new RuntimeException("Malformed URL: " + _urlString);
		int portStart = -1;
		int i = hostStart;
		
		//Parse the host and port
		for (; i < _urlString.length(); i++) {
			if (_urlString.charAt(i) == ':') {
				portStart = i;
			}
			if (_urlString.charAt(i) == '/') {
				if (portStart > hostStart) {
					//If a port symbol was detected, set the port and host
					_host = _urlString.substring(hostStart, portStart);
					_port = _urlString.substring(portStart + 1, i);
				} else { 
					_host = _urlString.substring(hostStart, i);
				}
				break;
			}
			if (i == _urlString.length() - 1) {
				if (_host.charAt(i) == '/') i--;
				_host = _urlString.substring(hostStart, i);
			}
		}
		if (_host == null) _host = _urlString.substring(hostStart);
		//Get the effective hostname
		if (_host.indexOf('.') == -1) _host = _host + ".local";
		
		//Parse the path
		int pathEnd = _urlString.lastIndexOf('/') + 1;
		if (pathEnd == hostStart) pathEnd = _urlString.length();
		_path = _urlString.substring(i, pathEnd);
		if (_path.length() == 0) _path = "/";
	}
	
	public String toString() { return _urlString; }
	public String getHost() { return _host; }
	public String getPort() { return _port; }
	public String getPath() { return _path; }
	public String getGenericDomain() { return _host.substring(_host.indexOf('.')); }
}
